package consoleUi;

import java.util.Vector;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

import app.kernel.api.PsgFacade;
import config.PSG_Configuration;

public class ConsoleMgr 
{
	PsgFacade psgKernelFacade = null;	
	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception 
	{
    	String defaultIP 		= PSG_Configuration.defaultIP;
    	int defaultPort 		= PSG_Configuration.defaultPort;
    	
//    	int appPort = PSG_Configuration.appPort;
    	
    	String IPPort = defaultIP+":"+defaultPort;
//    	String IPPort = defaultIP+":"+appPort;
    	String defaultMac = PSG_Configuration.PSGMAC;
//    	String ID_KEY = "http://"+defaultIP+ ":"+defaultPort+"/xmlrpc";
    	String ID_KEY 		= "http://"+defaultMac+"/xmlrpc";
    	ConsoleMgr consoleMgr = new ConsoleMgr();    	
    	consoleMgr.psgKernelFacade = new PsgFacade(ID_KEY, defaultIP, defaultPort);
    	
    	

		
    	String MSID = "";
    	String callerId = "";
    	String calleeId = "";
    	while(true)
    	{
	    	System.out.println("====================================");
	    	System.out.println("Welcome to Physical Space Gateway");
	    	System.out.println("====================================");
	    	System.out.println("(R) To REGISTER to the middleware");
	    	System.out.println("(C) To REGISTER CALLBACK to the middleware");
	    	System.out.println("(M) MOBILITY UPDATE");
	    	System.out.println("(D) To DELETE CALLBACK from middleware");
	    	System.out.println("(L) LEAVE middleware");
	    	System.out.println("(A) Abort Program");	    	
	    	System.out.println("====================================");
	    	System.out.print("Please key in your Cmd:");
	    	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
			String cmd = null;
			try 
			{
				cmd = in.readLine();
				System.out.println("====================================");
			} 
			catch (IOException e) 
			{
				e.printStackTrace();
			}
	        try
	        {
				if(cmd.equals("R"))
				{
			    	long beginOne = System.currentTimeMillis();
			    	MSID = consoleMgr.psgKernelFacade.register(IPPort);	
					System.out.println("The registered PSG MSID is: "+MSID);
			    	long endOne = System.currentTimeMillis();
			    	long psgRegistrationTime = endOne - beginOne;
			    	System.out.println("[PSG Registration Time]: "+psgRegistrationTime);
//			    	writeLog("psgRegistration", ""+psgRegistrationTime);
//					String MSID = consoleMgr.psgKernelFacade.register(IPPort);
//					System.out.println("The registered PSG MSID is: "+MSID);
				}
				else if(cmd.equals("C"))
				{
					for(int i = 0;i<25;i++){
//					consoleMgr.psgKernelFacade.leave();
			    	callerId = "12345:"+MSID;
			    	calleeId = "12345:"+"person@100000";
					long beginTwo = System.currentTimeMillis();
					String callbackRegistrationResult = consoleMgr.psgKernelFacade.registerCallback(ID_KEY, callerId, calleeId);
					System.out.println("[Callback Registration Result]: "+callbackRegistrationResult);
					long endTwo = System.currentTimeMillis();
					long callbackRegistrationTime = endTwo - beginTwo;
					System.out.println("[Callback Registration Time (Same CSG)]: "+callbackRegistrationTime);
					writeLog("callbackRegistration",""+callbackRegistrationTime);
					}
				}
				else if(cmd.equals("Q"))
				{
//					consoleMgr.psgKernelFacade.leave();

					long beginTwo = System.currentTimeMillis();
					System.out.print("Please key in your Query:");
					
			    	BufferedReader in2 = new BufferedReader(new InputStreamReader(System.in));
					String query = null;				
					query = in2.readLine();	
//					String query = "select name from person";
					String result =  consoleMgr.psgKernelFacade.queryMCS(query, ID_KEY);
					System.err.println("[Query Result]: "+result);
					long endTwo = System.currentTimeMillis();
					long queryTime = endTwo - beginTwo;
					System.out.println("[Query Time (Same CSG)]: "+queryTime);
//					writeLog("callbackRegistration",""+queryTime);
				}				
				else if(cmd.equals("M"))
				{
					
					long beginThree = System.currentTimeMillis();
					consoleMgr.psgKernelFacade.mobilityUpdate(MSID, IPPort);
					long endThree = System.currentTimeMillis();
					long mobilityUpdatingTime = endThree - beginThree;
					System.out.println("[Mobility Updating and Notification Time (same CSG and one callback)]: "+mobilityUpdatingTime);
					writeLog("mobilityUpdate",""+mobilityUpdatingTime);
//					System.out.print("Please key in your Query:");
//					
//			    	BufferedReader in2 = new BufferedReader(new InputStreamReader(System.in));
//					String query = null;				
//					query = in2.readLine();
//					consoleMgr.psgKernelFacade.queryMCS(query);
				}
				else if(cmd.equals("D")){
					long beginFour = System.currentTimeMillis();
					consoleMgr.psgKernelFacade.withdrawCallback(ID_KEY, callerId, calleeId);
					long endFour = System.currentTimeMillis();
					long callbackWithdrawingTime = endFour-beginFour;
					System.out.println("[Callback Withdrawing Time (same CSG)]: "+callbackWithdrawingTime);
					writeLog("deleteCallback",""+callbackWithdrawingTime);


				}
				else if(cmd.equals("L")){
			    	long beginFive = System.currentTimeMillis();
			    	consoleMgr.psgKernelFacade.leave(MSID);
//					System.out.println("The registered PSG MSID is: "+MSID);
			    	long endFive = System.currentTimeMillis();
			    	long psgLeaveTime = endFive - beginFive;
			    	System.out.println("[PSG De-Registration Time]: "+psgLeaveTime);
			    	writeLog("leave",""+psgLeaveTime);
				}
				else if(cmd.equals("I")){
			    	long beginFive = System.currentTimeMillis();
			    	String result = consoleMgr.psgKernelFacade.getIPPort(ID_KEY, MSID);
					System.out.println("The IPPort is: "+result);
			    	long endFive = System.currentTimeMillis();
			    	long psgLeaveTime = endFive - beginFive;
			    	System.out.println("[PSG De-Registration Time]: "+psgLeaveTime);
			    	writeLog("leave",""+psgLeaveTime);
				}
				else if(cmd.equals("A"))
				{
					break;
				}
				else
				{
					System.out.println("Incorrect Command, please try again.");
				}
	        }
	        catch (Exception e)
	        {
	        	System.err.println(e.getMessage());
	        }
    	}
	}
	
	//get updating alert
	public String getCurrentIp () throws UnknownHostException{
		String IP = ""+InetAddress.getLocalHost();
		System.out.println("The current IP is: "+IP);
		return IP;
	}
	
	// write experiment data to txt
	public static void writeLog(String fileName, String content)
    {
            try{
                FileWriter fstream = new FileWriter("D:\\Person\\"+fileName+".txt",true);
                BufferedWriter out = new BufferedWriter(fstream);
                out.write(content);
                out.write(System.getProperty( "line.separator" ));
                out.write(System.getProperty( "line.separator" ));
                //Close the output stream
                out.close();
                }
            catch (Exception e){//Catch exception if any
             System.err.println("Error: " + e.getMessage());}
    }

}
